import 'package:audioplayers/audioplayers.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:bboy_music_box_2023/bean/bean_music_manager.dart';
import 'package:bboy_music_box_2023/bean/bean_music_query.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_home.dart';
import 'package:get/get.dart';

class PlayCtrl extends GetxController {
  static PlayCtrl get to => Get.find();

  final isPlaying = false.obs;
  final player = AudioPlayer();
  final selectMusic = MusicManger().obs;

  //维护2个列表，已播放和待播放
  final musicEndArr = <Music>[].obs;
  final musicWaitArr = <Music>[].obs;

  @override
  void onInit() {
    player.onDurationChanged.listen((Duration d) {
      print('duration : ${d.inSeconds}');
      selectMusic.value.duration = d.inSeconds;
      selectMusic.refresh();
    });

    player.onPositionChanged.listen((Duration p) {
      selectMusic.value.seek = p.inSeconds;
      selectMusic.refresh();
    });

    player.onPlayerStateChanged.listen((PlayerState s) {
      print('Current player state: $s');
    });

    player.onPlayerComplete.listen((_) {
      skipNext();
    });

    player.onLog.listen(
      (String message) {
        print("log:$message");
      },
      onError: (Object e, [StackTrace? stackTrace]) async {
        print("log:$e,$stackTrace");
        if (isPlaying.value) {
          await tryToResume();
        }
      },
    );

    ever(isPlaying, (bool isPlay) async {
      if (isPlay) {
        await tryToResume();
      } else {
        await player.pause();
      }
    });
  }

  void skipPrevious() {
    int playingIndex = musicWaitArr.indexOf(selectMusic.value.music) - 1;
    if (playingIndex < 0) {
      playingIndex = 0;
    }
    playOrPause(musicWaitArr[playingIndex]);
  }

  void skipNext() {
    int playingIndex = musicWaitArr.indexOf(selectMusic.value.music) + 1;
    if (playingIndex >= musicWaitArr.length) {
      playingIndex = 0;
    }
    playOrPause(musicWaitArr[playingIndex]);
  }

  Future<void> tryToResume() async {
    print('play url: ${selectMusic.value.music!.url}');
    await player.setSourceUrl(
      Uri.encodeFull(
        selectMusic.value.music!.url,
      ),
    );
    await player.resume();
    String localTimeZone =
        await AwesomeNotifications().getLocalTimeZoneIdentifier();
    String utcTimeZone =
        await AwesomeNotifications().getLocalTimeZoneIdentifier();

    // await AwesomeNotifications().createNotification(
    //     content: NotificationContent(
    //       id: 10,
    //       channelKey: 'basic_channel',
    //       title: 'Notification every single minute',
    //       body: 'This notification was scheduled to repeat every minute.',
    //       icon: "assets/img/logo.png",
    //     ),
    //     schedule: NotificationInterval(
    //         interval: 60, timeZone: localTimeZone, repeats: true));
  }

  Future<void> playOrPause(Music music) async {
    bool isCurMusic = music.key == selectMusic.value.music?.key;
    selectMusic.value.music = music;
    selectMusic.refresh();
    bool curIsPlay = isPlaying.value;
    if (isCurMusic) {
      isPlaying.value = !curIsPlay;
    } else {
      isPlaying.value = true;
    }
    isPlaying.refresh();
  }

  @override
  void dispose() async {
    await player.dispose();
    super.dispose();
  }

  void seek(int seconds) async {
    await player.seek(Duration(seconds: seconds));
  }

  void replaceMusicWaitArr(List<Music> musics, Music selectMusic) {
    musicWaitArr.clear();
    musicWaitArr.addAll(musics);
    musicWaitArr.refresh();

    playOrPause(selectMusic);
  }

  void replaceMusicEndArr(List<Music> musics) {
    musicEndArr.addAll(musics);
    musicEndArr.refresh();
  }
}
